#!/bin/bash

# OpenCloudOS集群管理工具证书生成脚本

set -e

CERT_DIR="${1:-certs}"
mkdir -p "$CERT_DIR"

echo "生成TLS证书到目录: $CERT_DIR"

# 生成CA私钥
openssl genrsa -out "$CERT_DIR/ca.key" 2048

# 生成CA证书
openssl req -x509 -new -nodes \
    -key "$CERT_DIR/ca.key" \
    -sha256 -days 3650 \
    -out "$CERT_DIR/ca.crt" \
    -subj "/C=CN/ST=Beijing/L=Beijing/O=OpenCloudOS/OU=IT/CN=OpenCloudOS-CA"

# 生成服务器私钥
openssl genrsa -out "$CERT_DIR/server.key" 2048

# 生成服务器证书签名请求
openssl req -new -key "$CERT_DIR/server.key" \
    -out "$CERT_DIR/server.csr" \
    -subj "/C=CN/ST=Beijing/L=Beijing/O=OpenCloudOS/OU=IT/CN=localhost"

# 创建服务器证书扩展配置
cat > "$CERT_DIR/server.ext" << EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
DNS.2 = *.localhost
IP.1 = 127.0.0.1
IP.2 = 0.0.0.0
EOF

# 生成服务器证书
openssl x509 -req -in "$CERT_DIR/server.csr" \
    -CA "$CERT_DIR/ca.crt" \
    -CAkey "$CERT_DIR/ca.key" \
    -CAcreateserial \
    -out "$CERT_DIR/server.crt" \
    -days 365 \
    -extfile "$CERT_DIR/server.ext"

# 生成客户端私钥
openssl genrsa -out "$CERT_DIR/client.key" 2048

# 生成客户端证书签名请求
openssl req -new -key "$CERT_DIR/client.key" \
    -out "$CERT_DIR/client.csr" \
    -subj "/C=CN/ST=Beijing/L=Beijing/O=OpenCloudOS/OU=IT/CN=client"

# 创建客户端证书扩展配置
cat > "$CERT_DIR/client.ext" << EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = clientAuth
EOF

# 生成客户端证书
openssl x509 -req -in "$CERT_DIR/client.csr" \
    -CA "$CERT_DIR/ca.crt" \
    -CAkey "$CERT_DIR/ca.key" \
    -CAcreateserial \
    -out "$CERT_DIR/client.crt" \
    -days 365 \
    -extfile "$CERT_DIR/client.ext"

# 设置权限
chmod 600 "$CERT_DIR"/*.key
chmod 644 "$CERT_DIR"/*.crt

# 清理临时文件
rm -f "$CERT_DIR/server.csr" "$CERT_DIR/client.csr" "$CERT_DIR/server.ext" "$CERT_DIR/client.ext" "$CERT_DIR/ca.srl"

echo "证书生成完成！"
echo "CA证书: $CERT_DIR/ca.crt"
echo "服务器证书: $CERT_DIR/server.crt"
echo "服务器私钥: $CERT_DIR/server.key"
echo "客户端证书: $CERT_DIR/client.crt"
echo "客户端私钥: $CERT_DIR/client.key" 